package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.RoleMapper;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;
import com.itheima.health.vo.RoleVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();

        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryString)) {
            queryWrapper.like("name", queryString);
        }
        Page<Role> page = page(new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()), queryWrapper);

        List<Role> list = page.getRecords();

        List<RoleVO> voList = roleListToRoleVoList(list);

        return new PageResult(page.getTotal(), voList);
    }

    @Override
    public Boolean saveOrUpdatePermissionVo(RoleVO role) {
        boolean b = saveOrUpdate(role);
        //更新角色权限
        List<Integer> permissionList = role.getPermissionIds();
        baseMapper.deleteRolePermissionByRoleId(role.getId());
        for (Integer permissionId : permissionList) {
            baseMapper.addRolePermission(role.getId(),permissionId);
        }

        //更新角色菜单
        List<Integer> menuIds = role.getMenuIds();
        baseMapper.deleteRoleMenuByRoleId(role.getId());
        for (Integer menuId : menuIds) {
            baseMapper.addRoleMenu(role.getId(),menuId);
        }
        return b;
    }

    @Override
    public Boolean removeRoleById(Integer id) {

        baseMapper.deleteRolePermissionByRoleId(id);
        baseMapper.deleteRoleMenuByRoleId(id);
        boolean b = removeById(id);
        return b;
    }

    private List<RoleVO> roleListToRoleVoList(List<Role> list) {

        ArrayList<RoleVO> roleVOS = new ArrayList<>();
        for (Role role : list) {
            RoleVO roleVO = new RoleVO();
            roleVO.setDescription(role.getDescription());
            roleVO.setId(role.getId());
            roleVO.setKeyword(role.getKeyword());
            roleVO.setName(role.getName());
            roleVO.setPermissionIds(baseMapper.findRolePermissionByRoleId(role.getId()));
            roleVO.setMenuIds(baseMapper.findRoleMenuByRoleId(role.getId()));
            roleVOS.add(roleVO);
        }

        return roleVOS;
    }

}
